package net.qqxh.common.utils;

import org.apache.commons.io.FileUtils;

import java.io.*;

public class TxtCharsetUtil {
    public static String getCharset(byte[] file) throws IOException {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        InputStream bis = null;
        try {
            boolean checked = false;
            bis = new ByteArrayInputStream(file);
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1) {
                return charset;
            }
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8";
                checked = true;
            }
            bis.reset();
            if (!checked) {
                while ((read = bis.read()) != -1) {
                    if (read >= 0xF0) {
                        break;
                    }

                    if (0x80 <= read && read <= 0xBF) {
                        // 单独出现BF以下的，也算是GBK
                        break;
                    }

                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            // 双字节 (0xC0 - 0xDF)
                            continue;
                        }
                        // (0x80 - 0xBF),也可能在GB编码内
                        else {
                            break;
                        }

                    } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错，但是几率较小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else{
                                break;
                            }

                        } else{
                            break;
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                bis.close();
            }
        }
        return charset;

    }

    /**
     * 转换文本文件编码为utf8
     * 探测源文件编码,探测到编码切不为utf8则进行转码
     *
     * @param filePath 文件路径
     */
    public static void convertTextPlainFileCharsetToUtf8(String filePath, String topath) throws IOException {
        File sourceFile = new File(filePath);
        if (sourceFile.exists() && sourceFile.isFile() && sourceFile.canRead()) {
            String encoding = null;
            try {
                FileCharsetDetector.Observer observer = FileCharsetDetector.guessFileEncoding(sourceFile);
                // 为准确探测到编码,不适用猜测的编码
                encoding = observer.isFound() ? observer.getEncoding() : null;
                // 为准确探测到编码,可以考虑使用GBK  大部分文件都是windows系统产生的
            } catch (IOException e) {
                // 编码探测失败,
                e.printStackTrace();
            }

            if (encoding == null) {
                encoding = TxtCharsetUtil.getCharset(FileUtils.readFileToByteArray(sourceFile));
            }
            if (encoding != null && !"UTF-8".equals(encoding)) {
                // 不为utf8,进行转码
                File tmpUtf8File = new File(topath);
                File pf=new File( tmpUtf8File.getParent());
                  if(!pf.exists()){
                      pf.mkdirs();
                  }
                Writer writer = new OutputStreamWriter(new FileOutputStream(tmpUtf8File), "UTF-8");
                Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), encoding));
                char[] buf = new char[1024];
                int read;
                while ((read = reader.read(buf)) > 0) {
                    writer.write(buf, 0, read);
                }
                reader.close();
                writer.close();

            } else {
                FileUtils.copyFile(new File(filePath), new File(topath));
            }
        }
    }
}
